// SM4加密/解密功能
function initEncryptionFunctions(app) {
    // 扩展HttpRequestTool类，添加SM4加密/解密相关方法
    Object.assign(app, {
        async testEncrypt() {
            const inputElement = document.getElementById('sm4-input');
            const keyElement = document.getElementById('sm4-shared-key');
            const ivElement = document.getElementById('sm4-shared-iv');
            const outputElement = document.getElementById('sm4-output');

            if (!inputElement || !keyElement || !ivElement || !outputElement) {
                alert('页面元素未找到，请刷新页面重试');
                return;
            }

            const input = inputElement.value;
            const key = keyElement.value;
            const iv = ivElement.value;

            if (!input || !key || !iv) {
                alert('请填写完整的加密参数');
                return;
            }

            if (key.length !== 16) {
                alert('SM4密钥必须是16字节长度');
                return;
            }

            if (iv.length !== 16) {
                alert('SM4 IV必须是16字节长度');
                return;
            }

            try {
                const encrypted = await encryptSM4({
                    body: input,
                    key: key,
                    iv: iv
                });
                outputElement.value = encrypted;
                this.showMessage('加密成功');
            } catch (error) {
                alert('加密失败: ' + error.message);
            }
        },

        async testDecrypt() {
            const inputElement = document.getElementById('sm4-input');
            const keyElement = document.getElementById('sm4-shared-key');
            const ivElement = document.getElementById('sm4-shared-iv');
            const outputElement = document.getElementById('sm4-output');

            if (!inputElement || !keyElement || !ivElement || !outputElement) {
                alert('页面元素未找到，请刷新页面重试');
                return;
            }

            const input = inputElement.value;
            const key = keyElement.value;
            const iv = ivElement.value;

            if (!input || !key || !iv) {
                alert('请填写完整的解密参数');
                return;
            }

            if (key.length !== 16) {
                alert('SM4密钥必须是16字节长度');
                return;
            }

            if (iv.length !== 16) {
                alert('SM4 IV必须是16字节长度');
                return;
            }

            try {
                const decrypted = await decryptSM4({
                    body: input,
                    key: key,
                    iv: iv
                });
                outputElement.value = decrypted;
                this.showMessage('解密成功');
            } catch (error) {
                alert('解密失败: ' + error.message);
            }
        },

        copyResult() {
            const outputElement = document.getElementById('sm4-output');
            if (!outputElement) {
                alert('页面元素未找到，请刷新页面重试');
                return;
            }

            const result = outputElement.value;
            if (!result) {
                alert('没有可复制的结果');
                return;
            }

            navigator.clipboard.writeText(result).then(() => {
                this.showMessage('结果已复制到剪贴板');
            }).catch(() => {
                // 降级方案
                const textArea = document.createElement('textarea');
                textArea.value = result;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                this.showMessage('结果已复制到剪贴板');
            });
        },

        clearContent() {
            const inputElement = document.getElementById('sm4-input');
            const outputElement = document.getElementById('sm4-output');

            if (inputElement) inputElement.value = '';
            if (outputElement) outputElement.value = '';

            this.showMessage('内容已清空');
        },

        toggleKeyConfig() {
            const content = document.getElementById('key-config-content');
            const icon = document.querySelector('#key-config-toggle .toggle-icon');

            if (content.style.display === 'none') {
                content.style.display = 'block';
                icon.textContent = '▲';
                icon.style.transform = 'rotate(180deg)';
            } else {
                content.style.display = 'none';
                icon.textContent = '▼';
                icon.style.transform = 'rotate(0deg)';
            }
        }
    });
}

// 全局函数定义
async function encryptSM4(data) {
    try {
        const response = await fetch('/api/encrypt', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        });

        if (response.ok) {
            const result = await response.json();
            return result.encrypted;
        } else {
            throw new Error(`加密失败: ${response.status}`);
        }
    } catch (error) {
        throw new Error(`SM4加密失败: ${error.message}`);
    }
}

// 导出函数以便在其他文件中使用
window.initEncryptionFunctions = initEncryptionFunctions;

async function decryptSM4(data) {
    try {
        const response = await fetch('/api/decrypt', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        });

        if (response.ok) {
            const result = await response.json();
            return result.decrypted;
        } else {
            throw new Error(`解密失败: ${response.status}`);
        }
    } catch (error) {
        throw new Error(`SM4解密失败: ${error.message}`);
    }
}